import json

import requests
from langchain_openai import ChatOpenAI
from langchain.tools import BaseTool,StructuredTool,Tool
from langchain_core.utils.function_calling import convert_to_openai_function
from langchain_experimental.llms.ollama_functions import OllamaFunctions
from langchain_ollama import ChatOllama
from langchain.output_parsers import JsonOutputKeyToolsParser
from langchain.output_parsers.ernie_functions import JsonOutputFunctionsParser
from langchain.output_parsers.openai_functions import JsonKeyOutputFunctionsParser

api_key = "sk-6S0PtpNia71gjcfwSsDPsJ9mGqsVPr2XRQzAx1dHbJS7RW4t"
api_base="https://chatapi.littlewheat.com/v1"

open_weather_key = "5c939a7cc59eb8696f4cd77bf75c5a9a"

chat = ChatOpenAI(model="gpt-3.5-turbo",api_key=api_key ,base_url=api_base)

model = ChatOllama(model="qwen:7b-chat")
#print(model)
model.bind()

def get_weather(loc):
    """
        查询即时天气函数
        :param loc: 必要参数，字符串类型，用于表示查询天气的具体城市名称，\
        注意，中国的城市需要用对应城市的英文名称代替，例如如果需要查询北京市天气，则loc参数需要输入'Beijing'；
        :return：OpenWeather API查询即时天气的结果，具体URL请求地址为：https://api.openweathermap.org/data/2.5/weather\
        返回结果对象类型为解析之后的JSON格式对象，并用字符串形式进行表示，其中包含了全部重要的天气信息
        """
    # Step 1.构建请求
    url = "https://api.openweathermap.org/data/2.5/weather"

    # Step 2.设置查询参数
    params = {
        "q": loc,
        "appid": open_weather_key,  # 输入API key
        "units": "metric",  # 使用摄氏度而不是华氏度
        "lang": "zh_cn"  # 输出语言为简体中文
    }
    response = requests.get(url,params=params)
    data = response.json()
    return json.dump(data)

#get_weather_json_schema = json.dumps(convert_to_openai_function(get_weather),ensure_ascii=False)
#print(get_weather_json_schema)

#function_list = [get_weather_json_schema]
#print(function_list)
#chat.invoke()

#model = model.bind(function_list=function_list,
                   #function_call={"name": "get_weather"})
#print(model)
#res = model.invoke("查询下北京的天气")
#print(res)


#JsonKeyOutputFunctionsParser(key_name='loc', first_tool_only=True)

#res = "AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_KhcAfPhgY6adqs0am5WYqy16', 'function': {'arguments': '{\"loc\":\"Beijing\"}', 'name': 'get_weather'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 15, 'prompt_tokens': 198, 'total_tokens': 213}, 'model_name': 'gpt-3.5-turbo', 'system_fingerprint': 'fp_2f57f81c11', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-64d560b0-9485-4c6f-a7e3-a47fee73fa49-0', tool_calls=[{'name': 'get_weather', 'args': {'loc': 'Beijing'}, 'id': 'call_KhcAfPhgY6adqs0am5WYqy16'}])"
#parser = JsonOutputKeyToolsParser(key_name='loc', first_tool_only=True)
#ps = parser.parse_result(result=res)
#print(ps)

#AIMessage(content='', additional_kwargs={'function_call': {'name': 'get_weather', 'arguments': '{"loc": "\\u5317\\u4eac"}'}}, id='run-4bf84f61-c753-4621-ab70-f1e96bb62b7a-0')


# 实例化大模型
openai_chat = ChatOpenAI(model_name="gpt-3.5-turbo",api_key=api_key ,base_url=api_base)

# 绑定外部工具
llm_with_tools = openai_chat.bind_tools([get_weather])
print(llm_with_tools)
# 根据输入，调用指定的工具，并得到数据
chain = llm_with_tools | JsonOutputKeyToolsParser(key_name='get_weather', first_tool_only=True) | get_weather
weather_data = chain.invoke("今天北京的天气好吗？")
print(weather_data)